package com.emm.yixun.mobile.ui.analysis;

import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.mobile.R;
import com.emm.yixun.mobile.adapter.Analysis_work_adapter;
import com.emm.yixun.mobile.application.EmmApplication;
import com.emm.yixun.mobile.base.BaseActivity;
import com.emm.yixun.mobile.model.GetWorkloadStatisticsList;
import com.emm.yixun.mobile.model.GetWorkloadStatisticsList.WorkloadStatisticsList;
import com.eroad.product.tools.PickerView;
import com.eroad.product.tools.PickerView.onSelectListener;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.imid.swipebacklayout.lib.SwipeBackLayout;
import me.imid.swipebacklayout.lib.app.SwipeBackActivity;
import xf.tools.Loading;

/**
 * 
 * <p>
 * <b>Title：</b> 工作量统计
 * </p>
 * <p>
 * <b>Description：</b>
 * </p>
 * 
 * @author tangxin
 * @date 2016年12月6日 下午4:10:28
 */
public class AnalysisListViewActivity extends SwipeBackActivity {
	private static final String TAG = "AnalysisListViewActivity";

	/** 返回按钮 */
	ImageView back_btn;

	/** 标题 */
	TextView title_main;

	/** 统计表单列表 */
	ListView analysis_listview;

	/** 工作统计分析适配器 */
	Analysis_work_adapter adapter;

	TextView type_name1;

	LinearLayout select_1;

	/* ---公用选择框--- */
	View view;
	PopupWindow popu;
	/** 选中内容 */
	String selectName;
	/** 选中下标 */
	int SelectID;
	ArrayList<String> listname;

	/* ---公用选择框--- */

	/** 侧滑关闭框架 */
	private SwipeBackLayout mSwipeBackLayout;

	@Override
	protected void onResume() {
		BaseActivity.activity = this;
		super.onResume();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.analysis_activity);

		SetSwipeBackLayout(mSwipeBackLayout);

		BaseActivity.activity = this;

		initView();
		initBtn();
		getWorkloadStatisticsList("1");
	}

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 初始化view
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @author tangxin
	 * @date 2016年12月7日 上午11:37:47
	 */
	private void initView() {
		back_btn = (ImageView) findViewById(R.id.back_btn);
		title_main = (TextView) findViewById(R.id.title_main);
		title_main.setText(getString(R.string.analysis_title_list));
		analysis_listview = (ListView) findViewById(R.id.analysis_listview);
		type_name1 = (TextView) findViewById(R.id.type_name1);
		select_1 = (LinearLayout) findViewById(R.id.select_1);
		SetRelativiLayoutPadding(R.id.main_head_top_rela);
	}

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 初始化监听事件以及选项菜单
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @author tangxin
	 * @date 2016年12月7日 上午11:37:55
	 */
	private void initBtn() {
		back_btn.setVisibility(View.VISIBLE);
		back_btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		select_1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				listname = new ArrayList<String>();
				listname.add("今天");
				listname.add("昨天");
				listname.add("本周");
				listname.add("上周");
				listname.add("本月");
				listname.add("上月");
				listname.add("近三月");
				listname.add("今年");
				SetzpPopu(listname, "时间类型", type_name1);
			}
		});
	}

	/** 查询工作量统计 */
	GetWorkloadStatisticsList getworkload;

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 个人信息查询接口
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @param workloadTimeType
	 *            所选的时间
	 * @author tangxin
	 * @date 2016年12月7日 上午11:38:43
	 */
	private void getWorkloadStatisticsList(String workloadTimeType) {
		EmmApplication.updateUrl("getWorkloadStatisticsList");
		Map<String, String> map = new HashMap<String, String>();
		map.put("version", EmmApplication.getPackageManager(5));
		map.put("merchantId", EmmApplication.getData(EmmApplication.merchantId));
		map.put("token", EmmApplication.getToken());
		map.put("userId", EmmApplication.getUserId());
		map.put("terminalCode", EmmApplication.getPackageManager(2));
		map.put("projectCode", EmmApplication.getProjectCode());
		map.put("workloadTimeType", workloadTimeType);
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("params", map);
		JSONObject json = new JSONObject(paramsMap);
		String jsonstr = json.toString();
		RequestParams params = new RequestParams();
		params.put("body", jsonstr);
		Log.v("getWorkloadStatisticsList-->post", EmmApplication.urlStr + "?body=" + jsonstr);
		AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
		asyncHttpClient.post(EmmApplication.urlStr, params, new AsyncHttpResponseHandler() {
			@Override
			public void onFailure(Throwable error, String content) {
				super.onFailure(error, content);
				Loading.hideDialogForLoading();
				Log.v(TAG, "请求结束error:" + error + "==" + content);
			}

			@Override
			public void onFinish() {
				Loading.hideDialogForLoading();
				Log.v(TAG, "请求结束");
				super.onFinish();
			}

			@Override
			public void onStart() {
				super.onStart();
				Loading.showDialogForLoading(AnalysisListViewActivity.this, "正在加载...", false, true, 60000);
				Log.v(TAG, "请求开始");
			}

			@Override
			public void onSuccess(String content) {
				super.onSuccess(content);
				if (content == null) {
					return;
				}
				Log.v("content", "content=>" + content);
				JSONObject jsonObj = JSONObject.parseObject(content);
				JSONObject resData = (JSONObject) jsonObj.get("resData");
				if (resData == null) {
					Log.v(TAG, "信息返回值为空");
					return;
				}

				getworkload = JSONObject.parseObject(resData.toString(), GetWorkloadStatisticsList.class);

				if ("1".equals(getworkload.getResult())) {
					Log.v("获取成功", "");
					if (null != getworkload) {
						if (null != getworkload.getWorkloadStatisticsList()) {

							WorkloadStatisticsList w = new WorkloadStatisticsList();
							w.setUserName("总计");
							double followNum = 0;
							double addCustomerNum = 0;
							double payDepositNum = 0;
							double subscribeNum = 0;
							double signedNum = 0;
							for (int i = 0; i < getworkload.getWorkloadStatisticsList().size(); i++) {
								followNum += Double.valueOf(
										getworkload.getWorkloadStatisticsList().get(i).getFollowNum()).doubleValue();
								addCustomerNum += Double.valueOf(
										getworkload.getWorkloadStatisticsList().get(i).getAddCustomerNum())
										.doubleValue();
								payDepositNum += Double.valueOf(
										getworkload.getWorkloadStatisticsList().get(i).getPayDepositNum())
										.doubleValue();
								subscribeNum += Double.valueOf(
										getworkload.getWorkloadStatisticsList().get(i).getSubscribeNum()).doubleValue();
								signedNum += Double.valueOf(
										getworkload.getWorkloadStatisticsList().get(i).getSignedNum()).doubleValue();
							}
							w.setFollowNum(EmmApplication.drop2("" + followNum));
							w.setAddCustomerNum(EmmApplication.drop2("" + addCustomerNum));
							w.setPayDepositNum(EmmApplication.drop2("" + payDepositNum));
							w.setSubscribeNum(EmmApplication.drop2("" + subscribeNum));
							w.setSignedNum(EmmApplication.drop2("" + signedNum));
							getworkload.getWorkloadStatisticsList().add(w);

							if (null != adapter) {
								adapter.SetDate(getworkload.getWorkloadStatisticsList());
							} else {
								adapter = new Analysis_work_adapter(AnalysisListViewActivity.this, getworkload
										.getWorkloadStatisticsList());
								analysis_listview.setAdapter(adapter);
							}
						} else {
							EmmApplication.T("没有查询到数据");
							adapter.ClearDetails();
							if (null != adapter) {
								adapter.ClearDetails();
							} else {
							}
						}
					}
				} else {
					try {
						EmmApplication.T(getworkload.getErrorMsg().toString());
						Log.v("获取失败", "errorCode:" + getworkload.getErrorCode().toString() + "errorMsg:"
								+ getworkload.getErrorMsg().toString());
					} catch (NullPointerException e) {
						Log.v("获取失败", "NullPointerException->空指针");
					}
				}
			}
		});
	}

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 选项框
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @param listname
	 * @param title
	 * @param ed
	 * @author tangxin
	 * @date 2016年12月7日 上午11:39:07
	 */
	public void SetzpPopu(final List<String> listname, String title, final TextView ed) {
		view = LayoutInflater.from(AnalysisListViewActivity.this).inflate(R.layout.popu_zp, null);
		popu = new PopupWindow(view, android.support.v4.view.ViewPager.LayoutParams.FILL_PARENT,
				android.support.v4.view.ViewPager.LayoutParams.FILL_PARENT);
		popu.setFocusable(true);
		// EmmApplication.setNumberLog(AnalysisListViewActivity.this, 0.5f);//
		// 改变popupwindow范围外的屏幕亮度
		popu.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
		popu.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
		popu.showAtLocation(view, Gravity.BOTTOM, 0, 0);
		popu.showAsDropDown(view, 0, 0);
		popu.setFocusable(true);
		popu.setOutsideTouchable(true);
		view.setFocusable(true);
		view.setFocusableInTouchMode(true);
		view.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_BACK) {
					popu.dismiss();
					EmmApplication.setLog(AnalysisListViewActivity.this);
				}
				return false;
			}
		});
		view.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				popu.dismiss();
				EmmApplication.setLog(AnalysisListViewActivity.this);
			}
		});

		PickerView select_pick = (PickerView) view.findViewById(R.id.select_pick);
		selectName = listname.get(0);
		TextView shuerbtn = (TextView) view.findViewById(R.id.shuerbtn);
		RelativeLayout relative_all = (RelativeLayout) view.findViewById(R.id.relative_all);

		ImageView dis_btn = (ImageView) view.findViewById(R.id.dis_btn);
		dis_btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				popu.dismiss();
				EmmApplication.setLog(AnalysisListViewActivity.this);
			}
		});
		TextView title_select = (TextView) view.findViewById(R.id.title_select);
		title_select.setText(title);
		select_pick.setData(listname);
		select_pick.setOnSelectListener(new onSelectListener() {
			@Override
			public void onSelect(String text, int id) {
				selectName = text;
				SelectID = id;
			}
		});
		select_pick.setSelected(0);
		shuerbtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 确定
				popu.dismiss();
				EmmApplication.setLog(AnalysisListViewActivity.this);
				ed.setText(selectName);
				// 1、今天（默认）；2、昨天；3、本周；4、上周；5、本月；6、上月；7、近三月；8、今年
				String str = "1";
				if ("今天".equals(selectName)) {
					str = "1";
				} else if ("昨天".equals(selectName)) {
					str = "2";
				} else if ("本周".equals(selectName)) {
					str = "3";
				} else if ("上周".equals(selectName)) {
					str = "4";
				} else if ("本月".equals(selectName)) {
					str = "5";
				} else if ("上月".equals(selectName)) {
					str = "6";
				} else if ("近三月".equals(selectName)) {
					str = "7";
				} else if ("今年".equals(selectName)) {
					str = "8";
				}
				getWorkloadStatisticsList(str);
			}
		});
		relative_all.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
			}
		});
	}
}
